package tt.dz.egobus.servicemanager.business.listener.handler;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import tt.dz.egobus.api.managerservice.manager.RequestTask;
import tt.dz.egobus.servicemanager.bean.RedisTopicMessage;
import tt.dz.egobus.servicemanager.bean.SpringConfigConstant;
import tt.dz.egobus.servicemanager.business.key.BusinessCache;
import tt.dz.egobus.servicemanager.business.listener.RedisEventPublish;
import tt.dz.egobus.servicemanager.util.DateUtils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Anson
 * @date 17-9-7
 * @name 基于
 * @since 1.0.7
 */
@Component("businessIdExpireRedisEventPublish")
public class BusinessIdExpireRedisEventPublish implements RedisEventPublish {
    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessIdExpireRedisEventPublish.class);

    public static final String BUSINESS_CACHE_KEY = "BUSINESS_CACHE_KEY";
    public static final String BUSINESS_ID_KEY = "BUSINESS_CACHE_KEY";
    //发送短信的,最小间隔60S
    private static final long MIN_NOTIFY_LIMIT_MILISECONDS = 1000 * 60;

    private Boolean isOpenPublish = false;

    @Override
    public void publish(Map<String, Object> dataMap, RedisTemplate redisTemplate,
                        ApplicationContext applicationContext, Converter<String, RedisTopicMessage> converter) {
        if (!isOpenPublish) {
            return;
        }
        BusinessCache businessCache = (BusinessCache) dataMap.get(BUSINESS_CACHE_KEY);
        SpringConfigConstant springConfigConstant = applicationContext.getBean("springConfigConstant", SpringConfigConstant.class);
        //某一个任务抢单或者派单成功的时候,则需要进行下一步任务
        String businessId = businessCache.getBusinessId();
        if (StringUtils.isAnyEmpty(businessId) || converter == null) {
            return;
        }
        RedisTopicMessage redisTopicMessage = converter.convert(businessId);
        String redisKey = redisTopicMessage.toRedisEventKey();
        if (StringUtils.isAnyEmpty(redisKey)) {
            return;
        }
        RequestTask requestTask = businessCache.getRequestTask();
        long preNotifyTime = springConfigConstant.notifyMsgBeforeBespeakTimeLimitMinutes() * 60 * 1000;
        long bespeakTime = requestTask.getUserRequestInfo().getBespeakTime();
        long curTime = System.currentTimeMillis();
        long expireTime = bespeakTime - curTime + preNotifyTime;
        if (expireTime < MIN_NOTIFY_LIMIT_MILISECONDS) {
            //低于最小要求限制的时候
            expireTime = MIN_NOTIFY_LIMIT_MILISECONDS;
        }
        String timeStamp = DateUtils.DateToString(new Date(curTime + expireTime), DateUtils.DATE_TO_STRING_DETAIAL_PATTERN);
        LOGGER.info("发布一个短消息通知redis过期事件,business={},唤醒时间={}", businessId, timeStamp);
        redisTemplate.opsForValue().set(redisKey, businessCache.toJson());
        redisTemplate.expire(redisKey, expireTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void cancel(Map<String, Object> dataMap, RedisTemplate redisTemplate,
                       ApplicationContext applicationContext, Converter<String, RedisTopicMessage> converter) {
        if (!isOpenPublish) {
            return;
        }
        String businessId = (String) dataMap.get(BUSINESS_ID_KEY);
        if (StringUtils.isAnyEmpty(businessId) || converter == null) {
            return;
        }
        RedisTopicMessage redisTopicMessage = converter.convert(businessId);
        String redisKey = redisTopicMessage.toRedisEventKey();
        if (StringUtils.isAnyEmpty(redisKey)) {
            return;
        }
        LOGGER.info("取消一个短消息通知redis过期事件,business={},redis_key={}", businessId, redisKey);
        redisTemplate.delete(redisKey);
    }
}
